package com.cj.peiwan.server.order;

import com.cj.peiwan.entity.*;
import com.cj.peiwan.server.exception.ConflictException;
import com.cj.peiwan.server.exception.NotSpecifyIdException;
import com.cj.peiwan.server.other.*;
import com.taobao.api.ApiException;
import org.wei.utils.exception.NullResultExcepion;

import java.util.HashMap;
import java.util.Map;

public class OrderServiceImpl extends ABaseService implements IOrderService {

    // 淘宝通知会调用这个方法
    public void payOrder(String secret, Long orderId) {
        long now = System.currentTimeMillis();
        try {
            LockFactory.orderLock.lock();
            if (!"bihumanbu123A1!@abc".equals(secret)) {
                throw new ConflictException();
            }
            final Order order = orderDao.findBy(orderId);
            if (order.getStatus() != Order.STATUS_BEGIN) {
                throw new ConflictException("订单的状态不对，传入的状态为："
                        + order.getStatus());
            }
            PayOrderLog payOrderLog = new PayOrderLog();
            payOrderLog.setId(payOrderLogDao.getNextId());
            payOrderLog.setOrderId(orderId);
            payOrderLog.setTime(now);
            payOrderLogDao.insert(payOrderLog);
            Map<String, Object> operation = new HashMap<>();
            operation.put("status", Order.STATUS_PAYED);
            operation.put("createTime", now);
            operation.put("payedTime", now);
            orderDao.updateBy(orderId, operation);
            User user = userDao.findBy(order.getUserId());
            User peiwan = userDao.findBy(order.getPeiwanId());
            HuanxinSDK huanxinSDK = HuanxinSDK.getInstance();
            huanxinSDK.sendMessage(Global.userId2ChatId(user.getId()),
                    Global.userId2ChatId(peiwan.getId()), "我已经支付了订单，请与我保持联系");
            sendOrderPayedPhone(peiwan.getUsername(), user.getNickname());
        } catch (NullResultExcepion | ConflictException | NotSpecifyIdException e) {
            e.printStackTrace();
        } finally {
            LockFactory.orderLock.unlock();
        }
    }

    //用户充值
    public void payRecharge(String secret, Long rechargeId) {
        long now = System.currentTimeMillis();
        try {
            LockFactory.rechargeLock.lock();
            if (!"bihumanbu123A1!@abc".equals(secret)) {
                throw new ConflictException();
            }
            final Recharge recharge = rechargeDao.findBy(rechargeId);
            if (recharge.getStatus() != Recharge.STATUS_INIT) {
                throw new ConflictException("充值订单的状态不对，传入的状态为："
                        + recharge.getStatus());
            }
            RechargeLog rechargeLog = new RechargeLog();
            rechargeLog.setRechargeId(rechargeId);
            rechargeLog.setTime(now);
            rechargeLog.setId(rechargeLogDao.getNextId());
            rechargeLogDao.insert(rechargeLog);
            Map<String, Object> operation = new HashMap<>();
            operation.put("status", Order.STATUS_PAYED);
            operation.put("createTime", now);
            operation.put("payedTime", now);
            rechargeDao.updateBy(rechargeId, operation);
            // 用户充值金额增加，大于200标记可以创建工会
            User user = userDao.findBy(recharge.getUserId());
            if (user.getMoney2() == null) {
                user.setMoney2(0.0);
            }
            Map<String, Object> userOperation = new HashMap<>();
            userOperation.put("money2", user.getMoney2() + recharge.getMoney());
            if (recharge.getMoney() >= 200) {
                userOperation.put("canCreateUnion", 1);
            }
            userDao.updateBy(user.getId(), userOperation);
        } catch (NullResultExcepion | ConflictException | NotSpecifyIdException e) {
            e.printStackTrace();
        } finally {
            LockFactory.rechargeLock.unlock();
        }
    }

    private void sendOrderPayedPhone(final String phone,
                                     final String userNickname) {
        new Thread() {
            public void run() {
                try {
                    boolean ok = Alidayu.sendOrderMessage(userNickname, phone);
                    if (!ok) {
                        RongLian.sendOrderMessage(userNickname, phone);
                    }
                } catch (ApiException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }
}
